package com.block.sms.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.db.entity.SmsTemplate;
import com.block.db.mapper.SmsTemplateMapper;
import com.block.sms.cache.SmsTemplateCache;
import com.block.sms.service.ISmsTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * 
 * @since 2021-02-16
 */
@Service
public class SmsTemplateServiceImpl extends ServiceImpl<SmsTemplateMapper, SmsTemplate> implements ISmsTemplateService {

    @Autowired
    RedisTemplate<String, SmsTemplate> redisSmsTemplateTemplate;

    private  static  final  String SMS_TEMPLATE_INFO="SMS:TEMPLATE:INFO:{}:{}";

    @Override
    public SmsTemplate getSmsTemplate(String platform, String operationType, String appCode){
        SmsTemplate smsTemplate = this.baseMapper.getTemplateByPlatformAndOtype(platform, operationType, appCode);
        return smsTemplate;
    }

    @Override
    public SmsTemplate getAbleSmsTemplate(String operationType, String appCode){
        String redisKey = StrUtil.format(SMS_TEMPLATE_INFO, operationType, appCode);
        SmsTemplate smsTemplate = redisSmsTemplateTemplate.opsForValue().get(redisKey);
        if (smsTemplate == null) {
            smsTemplate = this.baseMapper.getTemplateByOperTypeAndAppCode( operationType, appCode);
            if (ObjectUtil.isEmpty(smsTemplate)){
                return null;
            }
            //放入map
            redisSmsTemplateTemplate.opsForValue().set(redisKey, smsTemplate, 4L, TimeUnit.HOURS);
        }
        return smsTemplate;
    }

}
